import React from "react";
import { BackHandler, UIManager } from "react-native";
import RootSiblings from "react-native-root-siblings";
import PreviewVideo from "@src/components/preview-video";
import Taro from "@tarojs/taro";



type Options = {
    src: string,
    triggerTarget?: Taro.Target
    success?: Function,
    fail?: Function,
    complete?: Function
}
export function previewVideo(obj: Options) {
    const { src, success, fail, complete, triggerTarget } = obj || {};

    let sibling;
    function backhandler() {
        onDestory();
        return true;
    }
    function onDestory() {
        console.log("destroy");
        BackHandler.removeEventListener("hardwareBackPress", backhandler);
        console.log(sibling, "sibling");
        sibling === null || sibling === void 0 ? void 0 : sibling.destroy();
        sibling = undefined;
    }
    function onSuccess() {
        const rsp = { errMsg: "previewVideo:ok" };
        onDestory();
        success === null || success === void 0 ? void 0 : success(rsp);
        complete === null || complete === void 0 ? void 0 : complete(rsp);
    }
    function onFail(e) {
        onDestory();
        fail === null || fail === void 0 ? void 0 : fail(Object.assign({ errMsg: "err" }, e));
        complete === null || complete === void 0 ? void 0 : complete("err", ...e);
    }


    let clickElementAnchor, initialSize;

    if (triggerTarget && triggerTarget.id) {
        UIManager.measure(Number(triggerTarget.id), (x, y, width, height, pageX, pageY) => {
            clickElementAnchor = { x: width / 2 + pageX, y: height / 2 + pageY };
            initialSize = { width, height };
            try {
                sibling = new RootSiblings(React.createElement(PreviewVideo, { onClose: onDestory, onLoad: onSuccess, src, clickElementAnchor, initialSize }));
                BackHandler.addEventListener("hardwareBackPress", backhandler);
            }
            catch (e) {
                onFail(e);
            }

        });
    } else {
        try {
            sibling = new RootSiblings(React.createElement(PreviewVideo, { onClose: onDestory, onLoad: onSuccess, src, clickElementAnchor, initialSize }));
            BackHandler.addEventListener("hardwareBackPress", backhandler);
        }
        catch (e) {
            onFail(e);
        }

    }







}